//jokere:app.use 加载用于处理http請求的middleware（中间件），当一个请求来的时候，会依次被这些 middlewares处理。
var express = require('express');
var path = require('path');

//设置favicon
var favicon = require('serve-favicon');

//加载日志中间件
var logger = require('morgan');

//解析cookie中间件
var cookieParser = require('cookie-parser');

//解析json中间件
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

//生成一个express实例
var app = express();

var passport = require("passport"),
GithubStrategy =  require("passport-github").Strategy;

var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var settings = require('./setting');
var flash = require('connect-flash');

app.use(session({
    secret: settings.cookieSecret,
    key: settings.db, //cookie name
    cookie: { maxAge: 1000 * 60 * 60 * 24 * 30 }, //30 days
    store: new MongoStore({
        url: `mongodb://${settings.host}:${settings.port}/${settings.db}`,
        db: settings.db,
        host: settings.host,
        port: settings.port
    })
}));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(flash());

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));

//connect内建中间件，用来解析请求体
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// app.use(bodyParser({keepExtensions:true,uploadDir:'./public/images'}));

//加载解析cookie的中间件
app.use(cookieParser());

//设置public为静态文件目录
app.use(express.static(path.join(__dirname, 'public')));
// app.use(express.static(path.join(__dirname, 'public')));

//路由控制器
app.use(passport.initialize());
app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
//页面匹配不到路由，会报错，这里可以处理到一个404 错误页面
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

passport.use(new GithubStrategy({
    clientID:"e8bc7c44e241f3354565",
    clientSecret:"f4ffd405bf964fffff65031e93e51b5cbbe61e7a",
    callbackURL:"http://118.24.28.250//login/github/callback"
},function(accessToken,refreshToken,profile,done){
    done(null,profile) 
}))

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;